﻿using System;
using System.Collections.Generic;
using System.Linq;
using Smo = Microsoft.SqlServer.Management.Smo;

namespace SWSP.Management.ServerObjects
{
    public class SqlTable : Table
    {
        #region Ctor

        public SqlTable(string tableName, Smo.Database database)
            : base(tableName)
        {
            // Create new table in memory
            _Table = database.Tables[this.Name];

            // Fill the properties
            FillProperties();
        }

        #endregion

        #region Private Properties

        private Smo.Table _Table;
        private List<SqlColumn> _SqlColumns = null;

        #endregion

        #region Public Properties

        public override List<Column> Columns
        {
            get
            {
                if (_Table == null)
                    return null;
                else
                {
                    foreach (Smo.Column column in _Table.Columns)
                    {
                        SqlColumn sqlColumn = new SqlColumn(column.Name, _Table);

                        // Add
                        _SqlColumns.Add(sqlColumn);
                    }

                    return _SqlColumns.Cast<Column>().ToList();
                }
            }
        }

        public override Column this[int index]
        {
            get
            {
                Smo.Column coloumn = _Table.Columns[index];

                if (coloumn == null)
                    return null;
                else
                {
                    return this.Columns[index];
                }
            }

            set
            {
                Columns[index] = value;
            }
        }

        #endregion

        #region Public Methods

        public override void Alter()
        {
            _Table.Alter();
        }

        public override void Create()
        {
            // Physically create the table in the database
           _Table.Create();
        }

        public override void Drop()
        {
            _Table.Drop();
        }

        public override void Rename(string newTableName)
        {
            _Table.Rename(newTableName);
        }

        #endregion

        #region Private Methods

        #region Private Methods

        private void FillProperties()
        {
            this.ID = _Table.ID;
            this.RowCount = _Table.RowCount;
            this._SqlColumns = new List<SqlColumn>();
        }

        #endregion
        
        #endregion
    }
}
